package com.aratek.salary.controller;

import com.alibaba.fastjson.JSONObject;
import com.aratek.salary.common.R;
import com.aratek.salary.service.SalaryReportSplitter;
import com.aratek.salary.service.Worker;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Yvan Jiang
 * @version 0.0.1
 * @Title FileUploader
 * @note 文件上传
 * @note Copyright 2016 by Aratek . All rights reserved
 * @time 2017/11/15
 **/
@Controller
@RequestMapping
public class FileUploader {

    @Autowired
    private Worker worker;

    private static final Logger LOG = LoggerFactory.getLogger(FileUploader.class);

    @RequestMapping("/")
    public String index(){
        return "/templates/index.html";
    }

    @ResponseBody
    @RequestMapping("/info")
    public R info() {
        StringBuilder msg;
        if(!SalaryReportSplitter.isWorking()){
            worker.cleanFile();
            msg = new StringBuilder("分发过程结束，上次记录总数" + worker.getTotal() + "，发送成功数" + worker.getSuccess());
        }else {
            msg = new StringBuilder("分发过程正在运行，总共需要分发" + worker.getTotal() + "，当前成功数" + worker.getSuccess());
        }
        List<JSONObject> errorList = new ArrayList<>();
        for(String str : Worker.getErrorList()){
            JSONObject object = new JSONObject();
            object.put("content", str);
            errorList.add(object);
        }
        return R.ok().put("msg", msg.toString()).put("errorList",errorList);
    }

    @ResponseBody
    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws IOException {
        LOG.info("文件已经上传");
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        File tempFile = File.createTempFile("salary", "."+FilenameUtils.getExtension(file.getOriginalFilename()));
        FileUtils.copyToFile(file.getInputStream(),tempFile);
        worker.startWork(tempFile);
        return R.ok().put("msg","服务已经启动");
    }
}
